import ldap, { Client } from "ldapjs"
import { Router } from "express"
import { IcallbackFn, Ioracle, IreturnObj } from "../../types"
import { logger } from "../../utils"

//const SERVERNAME = "ldap://10.2.220.1:389"

interface ServerList {
  [key:string]:string
}

const serverList:ServerList = {
  "xdomain":"ldap://10.2.220.1",
  "pdomain":"ldap://10.1.220.1",
  "qdomain":"ldap://10.9.220.1",
  "sdomain":"ldap://10.6.220.1"
}

export default (router: Router, oracle: Ioracle, callbackFn: IcallbackFn) => {
  //验证登陆
  router.post("/login", (req, res) => {
    const { useraccount, userpassword } = req.body
    let result: IreturnObj
    const domain = useraccount.substr(0,7)
    if(["xdomain","pdomain","qdomain","sdomain"].indexOf(domain) === -1) {
      result = {
        code: 200,
        message: "useraccount format error",
        data: [],
      }
      logger.info(`useraccount:${useraccount} 账号格式错误`)
      res.send(JSON.stringify(result))
    }

    if (!useraccount || !userpassword) {
      result = {
        code: 200,
        message: "useraccount or userpassword can not be null",
        data: [],
      }
      logger.info(`useraccount:${useraccount} 账号或密码为空`)
      res.send(JSON.stringify(result))
    } else {
      const serverName = serverList[domain as keyof ServerList]
      const client: Client = ldap.createClient({
        url: serverName,
      })
      client.bind(useraccount, userpassword, function (err) {
        if (err) {
          result = {
            code: 0,
            message: err.toString(),
            data: [],
          }
          logger.info(useraccount + " 验证失败")
          res.send(JSON.stringify(result))
        } else {
          //登陆成功返回人员信息
          let sql = " select * from user_info_n "
          sql += ` where account = '${useraccount}' `
          sql += " and job_status = 'employed' "
          logger.info(useraccount + " 验证成功")
          //callbackFn(res, oracle.connChaos, { sql })
          callbackFn(res, oracle.connChaos, { sql })
          //oracle.connChaos({sql}).then(res => result = res)
          /*result = {
            code: 200,
            message: "success",
            data: [],
          }*/
          logger.info(useraccount + " 验证成功")
        }
        client.unbind(function (err) {
          if (err) {
            logger.error("Error in unbinding: ", err)
            //console.log('Error in unbinding: ', err);
          } else {
            logger.info("Successfully unbound")
          }
        })
        //res.send(JSON.stringify(result))
      })
    }
  })

  return router
}
